<?php

defined('BASEPATH') or die('forbidden');

class Common_Controller Extends Controller {

    function index() {
        check_level(50);
    }

    function check_admin_loginfailure() {
        $username = addslashes($this->input->post("username"));
        $one = $this->db->one("SELECT loginfailure FROM {pre}admin WHERE username='{$username}'");
        if ($one && $one['loginfailure'] < 3) {
            json_output(1);
        } else {
            json_output(0);
        }
    }

    function autocomplete() {
        check_level(50);
        $fields = $this->input->post("fields");
        $table = $this->input->post("table");
        $query = $this->input->post("query");
        $areaId = $this->input->post("areaId");
        $fields = $fields ? $fields : "id,name";
        $fields = $table == "{pre}account_user" ? "user_id,nickname" : $fields;
        $fields = $table == "{pre}itemsample" ? $fields . ',itemType' : $fields;
        $fieldArr = explode(',', $fields);
        $where = array();
        foreach ($fieldArr as $m => $n) {
            $where[] = "`{$n}` LIKE '%{$query}%'";
        }
        $where = implode(' OR ', $where);
        if ($areaId && $table == '{pre}account_user') {
            $where = "areaId='{$areaId}' AND ({$where})";
        }
        $this->db->query("SELECT {$fields} FROM {$table} WHERE {$where}");
        $suggestions = array();
        while ($row = $this->db->get_array()) {
            $value = $table == '{pre}itemsample' ? $row[$fieldArr[1]] . (isset($row[$fieldArr[2]]) ? '[' . $row[$fieldArr[2]] . ']' : '') : $row[$fieldArr[1]];
            $suggestions[] = array_merge(array('data' => $row[$fieldArr[0]], 'value' => $value), $row);
        }
        $arr = array(
            'query' => $query,
            'suggestions' => $suggestions
        );

        echo json_encode_adv($arr);
    }

    function uid_valid() {
        $clientid = $this->input->get('clientid');
        if ($clientid == 'receiverObject') {
            $receiverObject = $this->input->get('receiverObject');
            if ($receiverObject != '0') {
                $receiverObject = str_replace(array("\r\n", "，"), ',', $receiverObject);
                if (preg_match("/^[0-9\,]+$/i", $receiverObject)) {
                    $ids = array_filter(array_unique(explode(',', $receiverObject)));
                    if ($ids) {
                        $one = $this->db->one("SELECT COUNT(*) AS nums FROM {pre}account_user WHERE user_id IN (" . implode(',', $ids) . ")");
                        if ($one['nums'] >= count($ids)) {
                            json_output(1, '');
                        } else {
                            json_output(0, translate('COMMON_VALID_NOT_EXIST_UID'));
                        }
                    } else {
                        json_output(0, translate('C_INVALID_PARAMS'));
                    }
                } else {
                    json_output(0, translate('C_INVALID_PARAMS'));
                }
            } else {
                json_output(1, '');
            }
        }
    }

    function help() {
        $module = segment(2);
        $this->view->display("common/help/{$module}");
    }

    function get_used_status() {
        return get_used_status();
    }

    function weigh() {
        check_level(50);
        //排序的数组
        $ids = $this->input->post("ids");
        //拖动的记录ID
        $changeid = $this->input->post("changeid");
        //操作的数据表
        $table = $this->input->post("table");
        //排序的方式
        $orderway = $this->input->post("orderway", 'strtolower');
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = array();
        $desc = explode(',', $ids);
        $this->db->query("SELECT id,weigh FROM {$table} WHERE id IN ('" . implode("','", $desc) . "') ORDER BY weigh {$orderway}");
        while ($row = $this->db->get_array()) {
            $sour[] = $row['id'];
            $weighdata[$row['id']] = $row['weigh'];
        }
        $position = array_search($changeid, $desc);
        $desc_id = $sour[$position];    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $desc_value = $weighdata[$desc_id];
        $sour_value = $weighdata[$sour_id];
        //echo "移动的ID:{$sour_id}\n";
        //echo "替换的ID:{$desc_id}\n";
        $temp = array_values(array_diff_assoc($desc, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            $this->db->query("UPDATE {$table} SET weigh='{$weighdata[$offset]}' WHERE id='{$n}'");
        }
        $c = 1;
        json_output($c, '');
        exit;
    }

    function wordsplit() {
        check_level(50);
        $word = $this->input->post("keyword");
        $split = ',';
        $this->split->load_dict();
        $result = array_reverse($this->split->do_split($word));
        return implode($split, $result);
    }

    function search() {
        check_level(50, 'user', 'user', 'index');
        if (is_submit()) {
            $keyword = trim(addslashes($this->input->post("keyword")));
            if (is_submit()) {
                if (!$keyword)
                    exit(0);
                $label = translate('COMMON_SEARCH_FIND_IS');
                if (stripos($keyword, "nickname:") !== false) {
                    $keyword = str_replace("nickname:", "", $keyword);
                    $where = "u.nickname = '{$keyword}'";
                    $field = translate('NICKNAME');
                } else if (stripos($keyword, "username:") !== false) {
                    $keyword = str_replace("username:", "", $keyword);
                    $where = "u.username = '{$keyword}'";
                    $field = translate('USERNAME');
                } else if (stripos($keyword, "openid:") !== false) {
                    $keyword = str_replace("openid:", "", $keyword);
                    $where = "u.openid = '{$keyword}'";
                    $field = translate('OPENID');
                } else if (is_numeric($keyword)) {
                    $where = "u.user_id = '{$keyword}' || u.openid='{$keyword}'";
                    $field = translate('UID') . "、" . translate('OPENID');
                } else if ((stripos($keyword, "id:") !== false)) {
                    $keyword = str_replace("id:", "", $keyword);
                    $where = "u.id = '{$keyword}'";
                    $field = "ID";
                } else {
                    $where = "u.nickname LIKE '%{$keyword}%' OR u.openid LIKE '%{$keyword}%'";
                    $field = translate('NICKNAMR') . "、" . translate('OPENID');
                    $label = translate('COMMON_SEARCH_FIND_INCLUDE');
                }
                $total = $this->db->one("SELECT COUNT(distinct id) AS num FROM {pre}account_user u WHERE {$where}");
                $link = $user = $result = $account = '';
                if ($total['num'] == 1) {
                    $row = $this->db->one("SELECT u.*,
                                                    a.id AS aid,a.type,a.username,a.jointime AS ajointime,a.logintime AS alogintime,a.deviceid,a.referer,a.sessionid,a.state,
                                                    aa.id AS aaid, aa.name, aa.url
                                                    FROM {pre}account_user u 
                                                    LEFT JOIN {pre}areasample aa ON u.areaId=aa.id
                                                    LEFT JOIN {pre}account a ON u.pf=a.pf AND u.openid=a.openid
                                                    WHERE {$where}");
                    $result = "<ins><span style='color:gray'>" . translate('COMMON_SEARCH_FIND') . " <font color=green>{$field}</font> {$label} <font color=green>{$keyword}</font> " . translate('COMMON_SEARCH_PLAYER_INFO') . "</span></ins>";
                    $user .= "<ins>" . translate('COMMON_SEARCH_BASIC_INFO') . "</ins>";
                    $user .= "<em><i>" . translate('UID') . "</i><b>{$row['user_id']}</b></em>";
                    $user .= "<em><i>" . translate('AREAID') . "</i><b>{$row['areaId']}</b></em>";
                    $user .= "<em><i>" . translate('VIRTUALID') . "</i><b>{$row['virtualId']}</b></em>";
                    $user .= "<em><i>" . translate('NICKNAME') . "</i><b>{$row['nickname']}</b></em>";
                    $user .= "<em><i>" . translate('LEVEL') . "</i><b>{$row['level']}</b></em>";
                    $user .= "<em><i>VIP</i><b>{$row['vip']}</b></em>";
                    $user .= "<em><i>" . translate('GOLDS') . "</i><b>{$row['golds']}</b></em>";
                    $user .= "<em><i>" . translate('GENDER') . "</i><b>" . ($row['sex'] == 0 ? translate('FEMALE') : translate('MALE') ) . "</b></em>";
                    $user .= "<em class='w'><i>" . translate('JOINTIME') . "</i><b>" . get_datetime($row['jointime']) . "</b></em>";
                    $user .= "<em class='w'><i>" . translate('LOGINTIME') . "</i><b>" . get_datetime($row['logintime']) . "</b></em>";
                    $user .= "<ins style='clear:both;width:100%;'>" . translate('COMMON_SEARCH_DETAIL_INFO') . "</ins>";
                    $params = array('url' => "user/user/info", 'data' => json_encode(array('id' => $row['user_id'])));
                    $params['sig'] = get_sig($params);
                    $url = str_replace("/api/", "", $row['url']) . site_url("api");
                    $user .= "<span id='detailinfo'><script type='text/javascript'>loadinfo('{$url}', " . json_encode($params) . ");</script><em style='width:300px'><i>" . translate('COMMON_SEARCH_LOADING') . "</i><b></b></em></span>";

                    $roles = array();
                    $this->db->query("SELECT * FROM {pre}account_user WHERE pf='{$row['pf']}' AND openid='{$row['openid']}' ORDER BY id DESC");
                    while ($it = $this->db->get_array()) {
                        $roles[] = "<a href='javascript:;' title='{$it['nickname']}&#13;" . translate('AREAID') . ":{$it['areaId']}&#13;" . translate('UID') . ":{$it['user_id']}' rel='{$it['id']}'>{$it['nickname']}({$it['areaId']})</a>";
                    }

                    $account = "<ins>" . translate('COMMON_SEARCH_ACCOUNT_INFO') . "</ins>";
                    $account .= "<div class='accountinner clear'><em><i>" . translate('COMMON_SEARCH_ACCOUNT_ID') . "</i><b>{$row['aid']}</b></em>";
                    $account .= "<em><i>" . translate('COMMON_SEARCH_ACCOUNT_TYPE') . "</i><b>{$row['type']}</b></em>";
                    $account .= "<em><i>" . translate('PF') . "</i><b>{$row['pf']}</b></em>";
                    $account .= "<em><i>" . translate('REFERER') . "</i><b>{$row['referer']}</b></em>";
                    $account .= "<em class='w'><i>OpenID</i><b>{$row['openid']}</b></em>";
                    //$account .= "<em><i>" . translate('NICKNAME') . "</i><b>{$row['nickname']}</b></em>";
                    //$stat .= "<em><i>" . translate('STATUS') . "</i><b>" . ($row['state'] == 0 ? translate('DIABLED') : translate('NORMAL')) . "</b></em>";
                    $account .= "<em class='w'><i>" . translate('JOINTIME') . "</i><b>" . get_datetime($row['ajointime']) . "</b></em>";
                    $account .= "<em class='w'><i>" . translate('LOGINTIME') . "</i><b>" . get_datetime($row['alogintime']) . "</b></em>";
                    $account .= "<em class='w'><i>" . translate('DEVICEID') . "</i><b style='width:140px;'>{$row['deviceid']}</b></em></div>";
                    $account .= "<ins style='clear:both;width:100%;'>" . translate('COMMON_SEARCH_OTHER_ROLE') . "</ins><em class='otherrole'><i></i><b>" . implode(' ', $roles) . "</b></em>";

                    $link .= "<ins>" . translate('COMMON_SEARCH_SHORTCUT') . "</ins>";
                    $baseurl = site_url();
                    $link .= "<a href='{$baseurl}account/user/edit/{$row['id']}' class='userdialog' title='" . translate('EDIT') . "' style='color:green'>" . translate('COMMON_SEARCH_EDIT_USER') . "</a>";
                    $link .= "<a href='{$baseurl}account/account/edit/{$row['aid']}' class='userdialog' title='" . translate('EDIT') . "' style='color:red'>" . translate('COMMON_SEARCH_EDIT_ACCOUNT') . "</a>";
                    $link .= "<a href='{$baseurl}order/order/index/?pf={$row['pf']}&openid={$row['openid']}' title='" . translate('MENU_ORDER_ORDER') . "' style='color:blue'>" . translate('MENU_ORDER_ORDER') . "</a>";
                    $link .= "<a href='{$baseurl}account/account/index/?pf={$row['pf']}&openid={$row['openid']}' title='" . translate('MENU_USER_USER') . "' style='color:blue'>" . translate('MENU_USER_USER') . "</a>";
                    $link .= "<a href='{$baseurl}mail/add/?user_id={$row['user_id']}' class='userdialog' title='" . translate('COMMON_SEARCH_MAIL') . "' style='color:#C24C16'>" . translate('COMMON_SEARCH_MAIL') . "</a>";
                    $link .= "<br /><a href='{$baseurl}account/user/forbidden/?id={$row['id']}' class='forbidden_words' title='" . translate('COMMON_SEARCH_FORBIDDEN_SINGLE') . "' style='color:gray'>" . translate('COMMON_SEARCH_FORBIDDEN_SINGLE') . "</a>";
                    $link .= "<a href='{$baseurl}account/user/forbidden/?aid={$row['aid']}' class='forbidden_words' title='" . translate('COMMON_SEARCH_FORBIDDEN_ALL') . "' style='color:gray'>" . translate('COMMON_SEARCH_FORBIDDEN_ALL') . "</a><b id='ft'></b>";
                } else if ($total['num'] > 0) {
                    $row = $this->db->simple("SELECT id,nickname,user_id,areaId FROM {pre}account_user u WHERE {$where} LIMIT 100");
                    $result .= "<ins><font color=green>" . translate('COMMON_SEARCH_RESULT', $total['num'], $keyword) . "</font></ins>";
                    $user .= "<ins>" . translate('COMMON_SEARCH_USER_LIST') . "</ins>";
                    foreach ($row as $m => $it) {
                        $user .= "<em><a href='javascript:;' title='{$it['nickname']}&#13;" . translate('AREAID') . ":{$it['areaId']}&#13;" . translate('UID') . ":{$it['user_id']}' rel='{$it['id']}'>{$it['nickname']}</a></em>";
                    }
                } else {
                    $user .= "<font color=red>" . translate('COMMON_SEARCH_NOT_FOUND') . "</font>";
                }
                echo $result ? "<li class='resultinfo clear'>{$result}</li>" : "";
                echo $user ? "<li class='userinfo clear'>{$user}</li>" : "";
                echo $account ? "<li class='accountinfo clear'>{$account}</li>" : "";
                echo $link ? "<li class='linkinfo clear'>{$link}</li>" : "";
            }
        } else {
            $this->view->display("common/search");
        }
    }

    function captcha() {
        $this->captcha->height = 22;
        $this->captcha->width = 55;
        $this->captcha->get();
    }

}